//
//  DateChoose.m
//  Tourism
//
//  Created by apple on 14-6-20.
//  Copyright (c) 2014年 com.youyi. All rights reserved.
//

#import "DatePOPView.h"
#import "DateModel.h"
#import "UIView+Hzl.h"
/** RGB设置颜色 */
#define RGB_COLOR(a,b,c,d) [UIColor colorWithRed:a/255.0 green:b/255.0 blue:c/255.0 alpha:d]
/** 物理屏幕的宽 */
#define ScreenWidth [UIScreen mainScreen].bounds.size.width

/** 物理屏幕的高 */
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
/** 设置字体大小*/
#define FONT_SIZE(s)  [UIFont systemFontOfSize:(s)]

@implementation DatePOPView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        CGFloat buttonW = self.width;
        CGFloat buttonH = self.height;
        
        UIButton *maskButton = [UIButton buttonWithType:UIButtonTypeCustom];
        maskButton.frame = CGRectMake(0, 0, buttonW, buttonH);
        maskButton.backgroundColor = RGB_COLOR(0,0,0,0.5);
        [maskButton addTarget:self action:@selector(getRemoveView) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:maskButton];
        NSLog(@"hah");
    }
    return self;
}

#pragma mark----加载数据
- (void)setMonthNum:(NSInteger)monthNum
{
    _monthNum = monthNum;
    
    self.dateArray = [NSMutableArray arrayWithCapacity:0];
    self.dayArray = [NSMutableArray arrayWithCapacity:0];
    NSInteger currentMonth = [self getMonthDate];
    //    NSInteger currentMonth = 2;
    NSInteger currentYear = [self getYearDate];
    NSInteger currentDay = [self getDayDate];
    //    NSInteger currentDay = 29;
    NSInteger currentDays = [self CaculateCurDayYear:currentYear  withmonth:currentMonth ];
    NSInteger laterDays = [self CaculateCurDayYear:currentYear-1  withmonth:currentMonth ];
    //    NSInteger laterDays = 28;
    if (currentDay >= laterDays) {
        _monthNum = 12;
        for(NSInteger i = 0;i < _monthNum;i++){
            NSInteger months = (currentMonth +i+1)%12;
            NSInteger isNow = (currentMonth +i+1)/12;
            if (months == 0) {
                months = 12;
                isNow = 0;
            }
            //            NSString *str1 = [NSString stringWithFormat:@"%ld年%ld月",currentYear+isNow,months];
            DateModel *model = [self getDateModelWithDate:currentYear-1+isNow :months];
            [self.dateArray addObject:model];
        }
    }else{
        _monthNum = 13;
        for(NSInteger i = 0;i < _monthNum;i++){
            NSInteger months = (currentMonth +i)%12;
            NSInteger isNow = (currentMonth +i)/12;
            if (months == 0) {
                months = 12;
                isNow = 0;
            }
            //            NSString *str1 = [NSString stringWithFormat:@"%ld年%ld月",currentYear+isNow,months];
            DateModel *model = [self getDateModelWithDate:currentYear-1+isNow :months];
            [self.dateArray addObject:model];
        }
    }
    
    for(NSInteger i = currentDay;i < currentDays ;i++){//开始显示的是上一年的本月
        NSInteger days = i+1;
        //            NSString *str2 = [NSString stringWithFormat:@"%ld日",days];
        DateModel *model = [self getDateModelWithDay:days];
        [self.dayArray addObject:model];
    }
    [self setMonthNum2:monthNum];//设置第二个
    [self getMainView];
    [self getAnimation];
}
- (void)setMonthNum2:(NSInteger)monthNum2
{
    _monthNum2 = monthNum2;
    
    self.dateArray2 = [NSMutableArray arrayWithCapacity:0];
    self.dayArray2 = [NSMutableArray arrayWithCapacity:0];
    NSInteger currentMonth = [self getMonthDate];
    //    NSInteger currentMonth = 2;
    NSInteger currentYear = [self getYearDate];
    NSInteger currentDay = [self getDayDate];
    //    NSInteger currentDay = 29;
    NSInteger currentDays = [self CaculateCurDayYear:currentYear  withmonth:currentMonth ];
    NSInteger laterDays = [self CaculateCurDayYear:currentYear-1  withmonth:currentMonth ];
    //    NSInteger laterDays = 28;
    if (currentDay >= laterDays) {
        _monthNum2 = 12;
        for(NSInteger i = 0;i < _monthNum2;i++){
            NSInteger months = (currentMonth +i+1)%12;
            NSInteger isNow = (currentMonth +i+1)/12;
            if (months == 0) {
                months = 12;
                isNow = 0;
            }
            //            NSString *str1 = [NSString stringWithFormat:@"%ld年%ld月",currentYear+isNow,months];
            DateModel *model = [self getDateModelWithDate:currentYear-1+isNow :months];
            [self.dateArray2 addObject:model];
        }
    }else{
        _monthNum2 = 13;
        for(NSInteger i = 0;i < _monthNum2;i++){
            NSInteger months = (currentMonth +i)%12;
            NSInteger isNow = (currentMonth +i)/12;
            if (months == 0) {
                months = 12;
                isNow = 0;
            }
            //            NSString *str1 = [NSString stringWithFormat:@"%ld年%ld月",currentYear+isNow,months];
            DateModel *model = [self getDateModelWithDate:currentYear-1+isNow :months];
            [self.dateArray2 addObject:model];
        }
    }
    
    for(NSInteger i = currentDay;i < currentDays ;i++){//开始显示的是上一年的本月
        NSInteger days = i+1;
        //            NSString *str2 = [NSString stringWithFormat:@"%ld日",days];
        DateModel *model = [self getDateModelWithDay:days];
        [self.dayArray2 addObject:model];
    }
}

#pragma mark----加载视图
- (void)getMainView
{
    mainView=[[UIView alloc]initWithFrame:CGRectMake(0,ScreenHeight,ScreenWidth,260)];
    mainView.backgroundColor = [UIColor whiteColor];
    [self addSubview:mainView];
    
    UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 120)/2.0,10,120,25)];
    lbl.text=@"选择日期";
    lbl.font=FONT_SIZE(14);
    lbl.textAlignment=NSTextAlignmentCenter;
    [mainView addSubview:lbl];
    
    UIView *dividerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
    dividerView.backgroundColor = [UIColor grayColor];
    [mainView addSubview:dividerView];
    
    UIButton *rtnBtn=[self getButton:@"取消"];
    rtnBtn.frame=CGRectMake(0,0,80,44.5);
    [mainView addSubview:rtnBtn];
    
    UIButton *setBtn=[self getButton:@"确定"];
    setBtn.frame=CGRectMake(ScreenWidth - 80,0,80,44.5);
    [mainView addSubview:setBtn];
    
    datePicker=[[UIPickerView alloc]initWithFrame:CGRectMake(0,30,ScreenWidth/2,215)];
    datePicker.dataSource=self;
    datePicker.delegate=self;
    [mainView addSubview:datePicker];
    
    datePicker2=[[UIPickerView alloc]initWithFrame:CGRectMake(ScreenWidth/2,30,ScreenWidth/2,215)];
    datePicker2.dataSource=self;
    datePicker2.delegate=self;
    [mainView addSubview:datePicker2];
    
}
- (UIButton*)getButton:(NSString*)title
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(getACtion:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}
#pragma mark----UIPickerView代理事件
//返回显示的列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}
//返回当前列显示的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(pickerView == datePicker){
        if(component==0)
        {
            return [self.dateArray count];
        }
        else if(component==1)
        {
            return [self.dayArray count];
        }
        
    }else if(pickerView == datePicker2){
        if(component==0)
        {
            return [self.dateArray2 count];
        }
        else if(component==1)
        {
            return [self.dayArray2 count];
        }
        
    }
    
    return 0;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 45;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if(component==0)
    {
        return 80;
    }
    else if(component==1)
    {
        return 50;
    }
    
    return 0;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *myView = nil;
    if(pickerView == datePicker){
        if (component == 0)
        {
            myView = [self getTimeLable:NSTextAlignmentCenter];
            myView.frame = CGRectMake(0, 0, 80, 45);
            
            DateModel *model = self.dateArray[row];
            
            myView.text = [self getTimeString:model];
            
        }
        else if (component == 1)
        {
            myView = [self getTimeLable:NSTextAlignmentRight];
            myView.frame = CGRectMake(ScreenWidth/2-50, 0, 50, 45);
            DateModel *model = self.dayArray[row];
            myView.text = [self getDayString:model];
        }
        
    }else if(pickerView == datePicker2){
        if (component == 0)
        {
            myView = [self getTimeLable:NSTextAlignmentCenter];
            myView.frame = CGRectMake(0, 0, 80, 45);
            
            DateModel *model = self.dateArray2[row];
            
            myView.text = [self getTimeString:model];
            
        }
        else if (component == 1)
        {
            myView = [self getTimeLable:NSTextAlignmentRight];
            myView.frame = CGRectMake(ScreenWidth/2-50, 0, 50, 45);
            DateModel *model = self.dayArray2[row];
            myView.text = [self getDayString:model];
        }
        
    }
    
    return myView;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(pickerView == datePicker){
        if(component == 0){
            DateModel *model = self.dateArray[row];
            //        UILabel *lable = (UILabel*)[datePicker viewForRow:row forComponent:component];
            //        lable.textColor = [UIColor redColor];
            
            NSInteger currentMonth = [self getMonthDate];
            //    NSInteger currentMonth = 2;
            NSInteger currentYear = [self getYearDate];
            NSInteger currentDay = [self getDayDate];
            NSInteger currentDays = [self CaculateCurDayYear:[model.year  integerValue]withmonth:[model.month integerValue]];
            //当前月
            if (([model.month integerValue]== currentMonth)&&([model.year integerValue]== currentYear)){
                [self.dayArray removeAllObjects];
                for(NSInteger i = 0;i < currentDay;i++){
                    NSInteger days = i+1;
                    //            NSString *str2 = [NSString stringWithFormat:@"%ld日",days];
                    if (days == currentDay) {//今天标记为0
                        days = 0;
                    }
                    DateModel *model = [self getDateModelWithDay:days];
                    [self.dayArray addObject:model];
                }
            }else if (([model.month integerValue]== currentMonth)&&!([model.year integerValue]== currentYear)){//上一年的本月
                [self.dayArray removeAllObjects];
                for(NSInteger i = currentDay;i < currentDays ;i++){
                    NSInteger days = i+1;
                    //            NSString *str2 = [NSString stringWithFormat:@"%ld日",days];
                    DateModel *model = [self getDateModelWithDay:days];
                    [self.dayArray addObject:model];
                }
            }else{
                [self.dayArray removeAllObjects];
                for(NSInteger i = 0 ;i < currentDays ;i++){
                    NSInteger days = i+1;
                    //            NSString *str2 = [NSString stringWithFormat:@"%ld日",days];
                    DateModel *model = [self getDateModelWithDay:days];
                    [self.dayArray addObject:model];
                }
                
            }
            [pickerView reloadComponent:1];
            
        }
        
    }else if(pickerView == datePicker2){
        if(component == 0){
            DateModel *model = self.dateArray2[row];
            //        UILabel *lable = (UILabel*)[datePicker viewForRow:row forComponent:component];
            //        lable.textColor = [UIColor redColor];
            
            NSInteger currentMonth = [self getMonthDate];
            //    NSInteger currentMonth = 2;
            NSInteger currentYear = [self getYearDate];
            NSInteger currentDay = [self getDayDate];
            NSInteger currentDays = [self CaculateCurDayYear:[model.year  integerValue]withmonth:[model.month integerValue]];
            //当前月
            if (([model.month integerValue]== currentMonth)&&([model.year integerValue]== currentYear)){
                [self.dayArray2 removeAllObjects];
                for(NSInteger i = 0;i < currentDay;i++){
                    NSInteger days = i+1;
                    //            NSString *str2 = [NSString stringWithFormat:@"%ld日",days];
                    if (days == currentDay) {//今天标记为0
                        days = 0;
                    }
                    DateModel *model = [self getDateModelWithDay:days];
                    [self.dayArray2 addObject:model];
                }
            }else if (([model.month integerValue]== currentMonth)&&!([model.year integerValue]== currentYear)){//上一年的本月
                [self.dayArray2 removeAllObjects];
                for(NSInteger i = currentDay;i < currentDays ;i++){
                    NSInteger days = i+1;
                    //            NSString *str2 = [NSString stringWithFormat:@"%ld日",days];
                    DateModel *model = [self getDateModelWithDay:days];
                    [self.dayArray2 addObject:model];
                }
            }else{
                [self.dayArray2 removeAllObjects];
                for(NSInteger i = 0 ;i < currentDays ;i++){
                    NSInteger days = i+1;
                    //            NSString *str2 = [NSString stringWithFormat:@"%ld日",days];
                    DateModel *model = [self getDateModelWithDay:days];
                    [self.dayArray2 addObject:model];
                }
                
            }
            [pickerView reloadComponent:1];
            
        }
        
    }
    
    
    
}
- (UILabel *)getTimeLable:(NSTextAlignment)alignment
{
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 45)];
    
    lable.textAlignment = alignment;
    
    lable.font = [UIFont systemFontOfSize:14];
    
    lable.backgroundColor = [UIColor clearColor];
    
    return lable;
}
#pragma mark----按钮事件
- (void)getACtion:(UIButton*)sender
{
    if ([sender.titleLabel.text isEqualToString:@"确定"])
    {
        //第一个pickview的数据
        NSInteger monthRow  = [datePicker selectedRowInComponent:(0)];
        NSInteger dayRow = [datePicker selectedRowInComponent:(1)];
        
        DateModel *model = self.dateArray[monthRow];
        DateModel *model1 = self.dayArray[dayRow];
        model.day = model1.day;
        //第二个pickview的数据
        NSInteger monthRow2  = [datePicker2 selectedRowInComponent:(0)];
        NSInteger dayRow2 = [datePicker2 selectedRowInComponent:(1)];
        
        DateModel *model2 = self.dateArray2[monthRow2];
        DateModel *model21 = self.dayArray2[dayRow2];
        model2.day = model21.day;
        
        [self.delegate ChooseDateModel:model model2:model2];
    }
    
    [self getRemoveView];
}
#pragma mark----私有方法
//获取当前的月数
- (NSInteger)getMonthDate{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    return [dateString integerValue];
}
//获取当前的年数
- (NSInteger)getYearDate{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    return [dateString integerValue];
}
//获取当前是第几天
- (NSInteger)getDayDate{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    return [dateString integerValue];
}
- (DateModel *)getDateModelWithDate:(NSInteger)year :(NSInteger)month
{
    DateModel *model = [[DateModel alloc]init];
    model.year = [NSString stringWithFormat:@"%ld",year];
    model.month = [NSString stringWithFormat:@"%ld",month];
    return model;
}
- (DateModel *)getDateModelWithDay:(NSInteger)day {
    DateModel *model = [[DateModel alloc]init];
    if(day == 0){
        model.day = @"今天";
    }else{
        model.day = [NSString stringWithFormat:@"%ld",day];
    }
    return model;
}
- (NSString*)getTimeString:(DateModel *)model{
    
    //yyyy-MM-dd
    
    NSString *string = [NSString stringWithFormat:@"%@年%@月",model.year,model.month];
    return [NSString stringWithFormat:@"%@",string];
    
}
- (NSString*)getDayString:(DateModel *)model{
    NSString *string =@"";
    //yyyy-MM-dd
    if([model.day isEqualToString:@"今天"]){
        string = model.day;
    }else{
        string = [NSString stringWithFormat:@"%@日",model.day];
    }
    return [NSString stringWithFormat:@"%@",string];
    
}
// 把时间转化为DateModel
- (DateModel *)getDateModelWithDate:(NSDate*)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear | NSCalendarUnitWeekday;
    NSDateComponents *nowCmps = [calendar components:unit fromDate:date];
    
    DateModel *model = [[DateModel alloc]init];
    model.date = date;
    model.year = [NSString stringWithFormat:@"%ld",nowCmps.year];
    model.month = [NSString stringWithFormat:@"%ld",nowCmps.month];
    model.day = [NSString stringWithFormat:@"%ld",nowCmps.day];
    model.hours = [NSString stringWithFormat:@"%ld",nowCmps.hour];
    model.minutes = [NSString stringWithFormat:@"%ld",nowCmps.minute];
    model.weak = [self getWeekday:nowCmps.weekday];
    
    return model;
}

// 判断显示的日期是周几
- (NSString*)getWeekday:(NSInteger)weakday
{
    switch (weakday - 1)
    {
        case 0:
            return @"周日";
            break;
        case 1:
            return @"周一";
            break;
        case 2:
            return @"周二";
            break;
        case 3:
            return @"周三";
            break;
        case 4:
            return @"周四";
            break;
        case 5:
            return @"周五";
            break;
        case 6:
            return @"周六";
            break;
            
        default:
            break;
    }
    
    return nil;
}
// 传入年份，月份得到该月总共有多少天
- (NSInteger)CaculateCurDayYear:(NSInteger)hYear withmonth:(NSInteger)hMonth
{
    NSInteger monthDays;
    
    char monthDay[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
    
    monthDays = monthDay[hMonth - 1];
    
    if (hMonth == 2)
    {
        // 判断是否是闰年,如果是闰年2月份是29天
        if ((((hYear % 4) == 0)&&((hYear % 100)!=0)) || ((hYear % 400) == 0))
        {
            monthDays = monthDays + 1;
        }
    }
    
    return monthDays;
}
#pragma mark----加载动画
- (void)getAnimation
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    
    mainView.frame = CGRectMake(0,ScreenHeight - mainView.height,ScreenWidth,mainView.height);
    
    [UIView commitAnimations];
}
- (void)getRemoveView
{
    [UIView animateWithDuration:0.2
                          delay:0.0
                        options:0
                     animations:^{
                         
                         [mainView setFrame:CGRectMake(0,ScreenHeight,ScreenWidth,mainView.height)];
                     }
                     completion:^(BOOL finished){
                         
                         [self removeFromSuperview];
                     }];
}


@end
